package com.roy.minimq.namesrv.service.processor;

import com.roy.minimq.common.broker.RegisterBrokerParam;
import com.roy.minimq.common.protocol.RequestCode;
import com.roy.minimq.namesrv.applicaton.NamesrvController;
import com.roy.minimq.remoting.domain.entity.CustomerCommandParam;
import com.roy.minimq.remoting.domain.entity.RemotingCommand;
import com.roy.minimq.remoting.domain.netty.NettyRequestProcessor;
import com.roy.minimq.remoting.domain.util.RemotingSysResponseCode;
import io.netty.channel.ChannelHandlerContext;

public class DefaultRequestProcessor implements NettyRequestProcessor {

    private NamesrvController namesrvController;

    public DefaultRequestProcessor(NamesrvController namesrvController) {
        this.namesrvController = namesrvController;
    }

    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws Exception {
        switch (request.getCode()) {
            case RequestCode.REGISTER_BROKER:
                return this.registerBroker(ctx,request);
            case RequestCode.UNREGISTER_BROKER:
                break;
            default:
                break;
        }
        return null;
    }
    //TODO broker注册的具体逻辑
    private RemotingCommand registerBroker(ChannelHandlerContext ctx, RemotingCommand request) {
        final CustomerCommandParam customerCommandParam = request.getCustomerCommandParam();
        try{
            RegisterBrokerParam registerBrokerParam = (RegisterBrokerParam)customerCommandParam;
            this.namesrvController.getRouteInfoManager().registerBroker(registerBrokerParam,ctx.channel());
            RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SUCCESS,"broker registered");
            return response;
        }catch(Exception e){

        }
        return null;

    }
    //TODO broker注销的具体逻辑
    private RemotingCommand unregisterBroker(ChannelHandlerContext ctx,RemotingCommand request){
        final CustomerCommandParam customerCommandParam = request.getCustomerCommandParam();
        try{
            RegisterBrokerParam registerBrokerParam = (RegisterBrokerParam)customerCommandParam;
            this.namesrvController.getRouteInfoManager().unregisterBroker(registerBrokerParam);
            RemotingCommand response = RemotingCommand.createResponseCommand(RemotingSysResponseCode.SYSTEM_ERROR,"broker registered");
            return response;
        }catch(Exception e){

        }
        return null;
    }

    @Override
    public boolean rejectRequest() {
        return false;
    }
}
